package session

import (
	"log"
	"net/http"

	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/e"
	"github.com/gin-gonic/gin"
)

func SessionAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = e.SUCCESS
		userID, isExits := c.Get("userID")
		if !isExits {
			log.Println("not get userID from context")
			c.Abort()
			return
		}
		userIDUint64 := userID.(uint64)
		var role string
		var isExist bool
		if userIDUint64 == 0 {
			log.Println("userID is not found")
			code = e.ERROR_AUTH
		} else {
			isExist, role = models.ExistsSession(userIDUint64)
			if !isExist {
				log.Println("user does not exist")
				code = e.ERROR_AUTH
			}
		}

		if code != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})
			c.Abort()
			return
		}

		c.Next()

		if status := c.Writer.Status(); status == http.StatusOK {
			err := models.PutSession(userIDUint64, role)
			if err != nil {
				log.Println(err)
			}
		}
	}
}

func SessionAdminAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = e.SUCCESS
		userID, isExists := c.Get("userID")
		if !isExists {
			log.Println("userID does not exist")
			c.Abort()
			return
		}
		userIDUint64 := userID.(uint64)
		var role string
		var isExist bool
		if userIDUint64 == 0 {
			log.Println("userID is not found")
			code = e.ERROR_AUTH
		} else {
			isExist, role = models.ExistsSession(userIDUint64)
			if !(isExist && role == "admin") {
				log.Printf("user isExist: %t, role: %s\n", isExist, role)
				code = e.ERROR_AUTH
			}
		}

		if code != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})
			c.Abort()
			return
		}

		c.Next()

		if status := c.Writer.Status(); status == http.StatusOK {
			err := models.PutSession(userIDUint64, role)
			if err != nil {
				log.Println(err)
			}
		}
	}
}
